package datasource;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class test {
    public static void main(String[] args) throws DocumentException, IOException {
        mergePdfFiles("output.pdf", "D:\\yummeng\\output.pdf");
    }

    /**
     * 合并原pdf为新文件
     *
     * @param files   pdf绝对路径集
     * @param newfile 新pdf绝对路径
     * @return
     */
    public static void mergePdfFiles(String files, String newfile) throws IOException, DocumentException {

        Document document = new Document(new PdfReader(files).getPageSize(1));
        PdfCopy copy = new PdfCopy(document, Files.newOutputStream(Paths.get(newfile)));
        document.open();
        PdfReader reader = new PdfReader(files);
        int n = reader.getNumberOfPages();
        for (int j = 1; j <= n; j++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, j);
            copy.addPage(page);
        }
        document.close();
    }

}
